<?php
namespace app\libs;

use Fate;
use app\libs\security\Crypt3DES;

class LibUser {

    /**
     * @return string
     */
    public static function encodeId($id) {
        return $id;
    }

    /**
     * @return string
     */
    public static function decodeId($idStr) {
        return $idStr;
    }

    /**
     * @return string 未加密的 uid
     */
    public static function getLoginUid() {
        if(!LibUser::isLogin()) {
            return '';
        }

        $prefix = Fate::$app->cookiePrefix;

        return $_COOKIE[$prefix . 'uid'];
    }

    public static function isLogin() {
        $key = Fate::$app->securityKey;
        $prefix = Fate::$app->cookiePrefix;

        if( !isset($_COOKIE[$prefix . 'uid']) ||
            !isset($_COOKIE[$prefix . 'str_uid']) ||
            !isset($_COOKIE[$prefix . 'salt']) ) {

            return false;
        }

        $uid = $_COOKIE[$prefix . 'uid'];
        $salt = $_COOKIE[$prefix . 'salt'];
        $strDecodeUid = LibUser::decodeId($_COOKIE[$prefix . 'str_uid']);

        $crypt = new Crypt3DES($key);

        if($uid === $strDecodeUid
            && ($crypt->encrypt('salt_' . $strDecodeUid) === $salt)) {
            return true;
        }

        return false;
    }

    public static function login($uid) {
        $key = Fate::$app->securityKey;
        $life = Fate::$app->cookieLife;
        $prefix = Fate::$app->cookiePrefix;

        $crypt = new Crypt3DES($key);
        $salt = $crypt->encrypt('salt_' . $uid);

        $time = time() + $life;

        setcookie($prefix . 'salt', $salt, $time, '/', '', false, true);
        setcookie($prefix . 'str_uid', LibUser::encodeId($uid), $time, '/');
        setcookie($prefix . 'uid', $uid ,$time, '/');
    }

    public static function logout() {
        $time = time() - 3600;
        $prefix = Fate::$app->cookiePrefix;

        setcookie($prefix . 'salt', '', $time, '/', '', false, true);
        setcookie($prefix . 'str_uid', '', $time, '/');
        setcookie($prefix . 'uid', '' ,$time, '/');
    }

}
